package com.server.questionbank.snframe.controller.Login;

import com.server.questionbank.snframe.config.interceptor.JwtInterceptor;
import com.server.questionbank.snframe.controller.Login.entity.LoginData;
import com.server.questionbank.snframe.domain.ResDTO.ResponseResult;
import com.server.questionbank.snframe.service.VerificationCode.VerificationCodeService;
import com.server.questionbank.snframe.service.UsersService.LoginsService;
import com.server.questionbank.snframe.util.JWT.JwtTokenProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/login")
public class LoginsController {
    @Autowired
    private JwtTokenProvider jwtTokenProvider;
    @Autowired
    private VerificationCodeService verificationCode;
    @Autowired
    private LoginsService loginsService;

    // 手机号登录
    @PostMapping("/phoneLogin")
    public ResponseResult<String> phoneLogin(@RequestBody LoginData loginData) {
        // 校验图片验证码
        ResponseResult<String> imageCodeResult = verificationCode.checkImageCode(loginData.getCode());
        if(imageCodeResult.getCode() != 200) return imageCodeResult;

        // 登录
        ResponseResult<Long> phoneLogin = loginsService.phoneLogin(loginData.getPhoneNumber(), loginData.getPassword());
        if(phoneLogin.getCode() != 200) return ResponseResult.error(phoneLogin.getMessage());

        // 生成token
        String token = jwtTokenProvider.generateToken(phoneLogin.getData().toString());

        // 返回token
        return ResponseResult.success("登录成功", token);
    }

    // 判断token是否过期
    @PostMapping("/isTokenExpired")
    public ResponseResult<Boolean> isTokenExpired() {
        Long userId = -1L;
        try {
            userId = Long.valueOf(JwtInterceptor.getCurrentUser());
        } catch (Exception e) {
            return ResponseResult.success("已过期", true);
        }
        if (userId == null || userId <= 0) { return ResponseResult.success("已过期", true); }
        return ResponseResult.success("未过期", false);
    }
}
